package com.jds.test.consoleim;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by sunyuming on 18/8/1.
 */
class ServerHandler4 extends SimpleChannelInboundHandler<BaseBean> {

    private static AttributeKey<String> userName = AttributeKey.valueOf("userName");

    //读取客户端发送的数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BaseBean msg) throws Exception {
        int type = msg.getType();
        if(type == 0) {
            String user = msg.getText();
            String text = user + " - 上线";
            System.out.println(text);
            BaseBean baseBean = new BaseBean();
            baseBean.setText(text);
            Server4.CHANNEL_GROUP.writeAndFlush(baseBean);
            ctx.channel().attr(userName).set(user);
        } else {
            BaseBean baseBean = new BaseBean();
            baseBean.setText(ctx.channel().attr(userName).get() + " - " + msg.getText());
            Server4.CHANNEL_GROUP.writeAndFlush(baseBean);
        }

    }

    //新客户端接入
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("新连接");
        Server4.CHANNEL_GROUP.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String user = ctx.channel().attr(userName).get();
        String text = user + " - 下线";
        System.out.println(text);

        BaseBean baseBean = new BaseBean();
        baseBean.setText(text);
        Server4.CHANNEL_GROUP.writeAndFlush(baseBean);
    }

    //异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
        cause.printStackTrace();
    }
}